﻿namespace Ocelot.Admin.Api.Web.Core.Extensions
{
    public static class SqlsugarExtensions
    {
        public static void AddSqlsugarSetup(this IServiceCollection services)
        {
            SqlSugarScope sqlSugar = new(
                // 读取 appsettings.json 中的 ConnectionConfigs 配置节点
                App.GetConfig<List<ConnectionConfig>>("ConnectionConfigs"),
                db =>
                {
                    //单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        //执行时间超过1秒
                        if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
                        {
                            //代码CS文件名
                            var fileName = db.Ado.SqlStackTrace.FirstFileName;
                            //代码行数
                            var fileLine = db.Ado.SqlStackTrace.FirstLine;
                            //方法名
                            var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
                            Console.WriteLine($"执行时间超过1秒，建议优化，fileName：{fileName}，fileLine：{fileLine}，FirstMethodName：{FirstMethodName}，sql：{sql}");
                        }
                        Console.WriteLine($"SQL:{sql}，pars：{pars}");
                    };

                    var now = DateTimeOffset.Now.ToUnixTimeSeconds();//取Unix时间戳
                    db.Aop.DataExecuting = (oldValue, entityInfo) =>
                    {
                        switch (entityInfo.OperationType)
                        {
                            case DataFilterType.InsertByObject:
                                if (entityInfo.PropertyName == "CreateTime")
                                    entityInfo.SetValue(now);
                                if (entityInfo.PropertyName == "UpdateTime")
                                    entityInfo.SetValue(now);
                              
                                break;
                            case DataFilterType.UpdateByObject:
                                if (entityInfo.PropertyName == "UpdateTime")
                                    entityInfo.SetValue(now);
                                break;
                        }
                    };
                });
            services.AddSingleton<ISqlSugarClient>(sqlSugar);
        }
    }
}
